package com.soulmate.cart.service;

import common.pojo.Cart;
import common.pojo.Product;
import com.soulmate.cart.mapper.CartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
public class CartServiceImpl implements CartService{
    @Autowired
    private CartMapper cartMapper=null;
    @Autowired
    private RestTemplate client=null;

    @Override
    public List<Cart> findCartsByUserId(String userId) {
        List<Cart> cartList=cartMapper.findCartsByUserId(userId);
        return cartList;
    }

    @Override
    public void addCart(Cart cart) {
        /*1 判断当前用户是否添加过这个商品到购物车
            查询数据库 userId productId
          2 exist==null:说明新增 insert
          3 exist!=null: 将旧num+新num更新到数据库
         */
        //通过userId productId 两个字段定位。
        Cart exist=cartMapper.findExistCart(cart);
        //if判断
        if (exist==null){
            //TODO 调用商品微服务完成数据封装
            //缺少3个字段 image name price 商品系统访问单个商品查询
            Product product=client.getForObject("http://productservice/product/manage/item/" + cart.getProductId(),Product.class);
            cart.setProductImage(product.getProductImgurl());
            cart.setProductName(product.getProductName());
            cart.setProductPrice(product.getProductPrice());
            //插入到购物车
            cartMapper.insertCart(cart);
        }else {
            //非空说明更新num
            //更新内存对象num
            cart.setNum(exist.getNum()+cart.getNum());
            //持久层更新 update t_cart set num=#{num}
            //where userId productId
            cartMapper.updateNumByCart(cart);
        }
    }

    @Override
    public void updateNum(Cart cart) {
        cartMapper.updateNumByCart(cart);
    }

    @Override
    public void deleteCart(Cart cart) {
        cartMapper.deleteCart(cart);
    }


}
